package com.example.rentalclearing.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@RequiredArgsConstructor
public class ThreadPoolConfig {

    private final ClearingConfig clearingConfig;

    @Bean("clearingExecutor")
    public Executor clearingExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数，根据数据库连接池大小和IO密集型特点设置
        int corePoolSize = Math.min(clearingConfig.getBatchThreads(), 30);
        executor.setCorePoolSize(corePoolSize);
        // 最大线程数，应对高峰期负载，但不应超过数据库连接数
        int maxPoolSize = Math.min(clearingConfig.getBatchThreads() * 2, 60);
        executor.setMaxPoolSize(maxPoolSize);
        // 队列容量，平衡内存使用和任务缓存
        executor.setQueueCapacity(200);
        // 线程名称前缀
        executor.setThreadNamePrefix("clearing-thread-");
        // 拒绝策略，防止任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 优雅关闭配置
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        // 线程空闲回收时间
        executor.setKeepAliveSeconds(60);
        executor.initialize();
        return executor;
    }
}